package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {

    @Autowired
    ApLikesBehaviorService apLikesBehaviorService;
    @Autowired
    ApUnlikesBehaviorService apUnlikesBehaviorService;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;


    /**
     * 查询用户文章的点赞\不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        // 预封装结果
        Map resultMap = new HashMap<>();
        resultMap.put("islike", false);
        resultMap.put("isunlike", false);

        // 参数校验
        if (dto == null || dto.getArticleId() == null || dto.getEntryId() == null) {
            return resultMap;
        }
        /**
         * 实体类型
         *  0 终端设备
         *  1 用户
         */
        // 查询行为实体
        ApBehaviorEntry behaviorEntry = null;
        if (dto.getType() == 1) {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        } else {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEntryId());
        }
        if (behaviorEntry == null) {
            return resultMap;
        }
        // 行为实体ID
        resultMap.put("entryId", behaviorEntry.getId());
        // 查询文章点赞
        ApLikesBehavior apLikesBehavior = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getEntryId,behaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId,dto.getArticleId())
        );
        if (apLikesBehavior != null && apLikesBehavior.getOperation()==0) {
            resultMap.put("islike", true);
        }

        // 查询文章不喜欢
        ApUnlikesBehavior apUnlikesBehavior = apUnlikesBehaviorService.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getEntryId,behaviorEntry.getId())
                .eq(ApUnlikesBehavior::getArticleId,dto.getArticleId())
        );
        if (apUnlikesBehavior != null && apUnlikesBehavior.getType().intValue() == 0) {
            resultMap.put("isunlike", true);
        }

        return resultMap;
    }
}